import React, { Component } from 'react';
import matchPath from '../utils/matchPath';
import RouterContext from '../RouterContext';

export default class Switch extends Component {
  render() {
    return (
      <RouterContext.Consumer>
        {(context) => {
          let match; // 记录是否匹配
          let element; // 记录匹配的元素

          const { location } = context;

          /* 遍历子组件，找到第一个匹配的 */
          React.Children.forEach(this.props.children, (child) => {
            if (match == null && React.isValidElement(child)) {
              element = child;
              match = child.props.path ? matchPath(location.pathname, child.props) : context.match;
            }
          });

          return match ? React.cloneElement(element, { computedMatch: match }) : null;
        }}
      </RouterContext.Consumer>
    );
  }
}
